package com.reactnativewechatts.wxapi;

import android.content.Intent;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;

import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.WritableMap;
import com.reactnativewechatts.WechatTsModule;
import com.tencent.mm.opensdk.constants.ConstantsAPI;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.modelpay.PayResp;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

public class WXPayEntryActivity extends AppCompatActivity implements IWXAPIEventHandler {
  private IWXAPI api;
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    api = WXAPIFactory.createWXAPI(this, WechatTsModule.appId);

    try {
      Intent intent = getIntent();
      api.handleIntent(intent, this);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  @Override
  protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);

    setIntent(intent);
    api.handleIntent(intent, this);
  }

  @Override
  public void onReq(BaseReq baseReq) {

    finish();
  }

  @Override
  public void onResp(BaseResp baseResp) {
    WritableMap map = Arguments.createMap();
    map.putInt("errCode", baseResp.errCode);

    if (baseResp.getType() == ConstantsAPI.COMMAND_SENDAUTH) {
      SendAuth.Resp resp = (SendAuth.Resp) (baseResp);

      map.putString("type", "SendAuth.Resp");
      map.putString("code", resp.code);

    } else if (baseResp.getType() == ConstantsAPI.COMMAND_PAY_BY_WX) {
      PayResp resp = (PayResp) (baseResp);
      map.putString("type", "PayReq.Resp");
      map.putString("returnKey", resp.returnKey);

    }

    WechatTsModule.promise.resolve(map);
    finish();
  }
}
